<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h2>对象数组去重</h2>
<script>
    var songs = [
        {name:"羽根",artist:"air"},
        {name:"羽根",artist:"air"},
        {name:"晴天",artist:"周杰伦"},
        {name:"晴天",artist:"周杰伦"},
        {artist:"周杰伦",name:"晴天"}
    ];

    function unique(songs){
        let result = {};
        let finalResult=[];
        for(let i=0;i<songs.length;i++){
            result[songs[i].name]=songs[i];
            //因为songs[i].name不能重复,达到去重效果,且这里必须知晓"name"或是其他键名
        }
        //console.log(result);{"羽根":{name:"羽根",artist:"air"},"晴天":{name:"晴天",artist:"周杰伦"}}
        //现在result内部都是不重复的对象了，只需要将其键值取出来转为数组即可
        for(item in result){
            finalResult.push(result[item]);
        }
        //console.log(finalResult);[{name:"羽根",artist:"air"},{name:"晴天",artist:"周杰伦"}]
        return finalResult;
    }

    /*
     * JSON数组去重
     * @author Hongwei Yang
     * @param: [array] json Array
     * @param: [string] 唯一的key名，根据此键名进行去重
     */
    function uniqueArray(array, key) {
        var result = [array[0]];
        for (var i = 1; i < array.length; i++) {
            var item = array[i];
            var repeat = false;
            for (var j = 0; j < result.length; j++) {
                if (item[key] == result[j][key]) {
                    repeat = true;
                    break;
                }
            }
            if (!repeat) {
                result.push(item);
            }
        }
        return result;
    }


    console.log(unique(songs));
    console.log(uniqueArray(songs,'name'));

</script>
</body>
</html>